<template>
  <div class="layout">
    <!--    管理端布局-->
    <el-container v-if="state.adminMenu" class="container">
      <el-aside class="aside">
        <div class="head">
          <img :src="logoImage" alt="logo"/>
        </div>
        <div class="line"/>
        <el-menu
            background-color="#1F3A5F"
            text-color="#fff"
            :router="true"
            :default-openeds="state.defaultOpen"
            :default-active="state.currentPath"
        >
          <!-- 系统首页 -->
          <el-menu-item-group>
            <el-menu-item index="/system/homePage">
              <el-icon>
                <Shop/>
              </el-icon>
              系统首页
            </el-menu-item>
          </el-menu-item-group>

          <!-- 信息管理 -->
          <el-sub-menu index="2">
            <template #title>
              <span>信息管理</span>
            </template>
            <el-menu-item-group>
              <el-menu-item index="/information/classify">
                <el-icon>
                  <Menu/>
                </el-icon>
                资讯分类
              </el-menu-item>
              <el-menu-item index="/information/info">
                <el-icon>
                  <Document/>
                </el-icon>
                资讯信息
              </el-menu-item>
              <el-menu-item index="/activity/public">
                <el-icon>
                  <Promotion/>
                </el-icon>
                公益活动
              </el-menu-item>
              <el-menu-item index="/activity/register">
                <el-icon>
                  <Goods/>
                </el-icon>
                活动报名
              </el-menu-item>
              <el-menu-item index="/service/pension">
                <el-icon>
                  <Service/>
                </el-icon>
                养老服务
              </el-menu-item>
              <el-menu-item index="/service/appointment">
                <el-icon>
                  <Clock/>
                </el-icon>
                服务预约
              </el-menu-item>
              <el-menu-item index="/nursing/home">
                <el-icon>
                  <OfficeBuilding/>
                </el-icon>
                养老院信息
              </el-menu-item>
              <el-menu-item index="/comment/info">
                <el-icon>
                  <ChatLineRound/>
                </el-icon>
                评论信息
              </el-menu-item>
              <el-menu-item index="/announcement/info">
                <el-icon>
                  <Bell/>
                </el-icon>
                公告信息
              </el-menu-item>

              <el-menu-item index="/video/info">
                <el-icon>
                  <VideoCamera/>
                </el-icon>
                视频信息
              </el-menu-item>

            </el-menu-item-group>
          </el-sub-menu>
          <!-- 用户管理 -->
          <el-sub-menu index="3">
            <template #title>
              <span>用户管理</span>
            </template>
            <el-menu-item-group>
              <el-menu-item index="/user/info">
                <el-icon>
                  <User/>
                </el-icon>
                用户信息
              </el-menu-item>
              <el-menu-item index="/user/updatePwd">
                <el-icon>
                  <Lock/>
                </el-icon>
                修改密码
              </el-menu-item>
            </el-menu-item-group>
          </el-sub-menu>
        </el-menu>
      </el-aside>
      <el-container class="content">
        <AdminHeader/>
        <div class="main">
          <router-view/>
        </div>
        <AdminFooter/>
      </el-container>
    </el-container>
    <!-- 客户端布局 -->
    <el-container v-else-if="state.clientMenu" class="content">
      <!-- 头部导航栏 -->
      <ClientHeader/>
      <!-- 内容部 -->
      <el-container class="content">
        <router-view/>
      </el-container>
      <!-- 底部栏 -->
      <!--      <AdminFooter/>-->
    </el-container>
    <!--    登录注册路由-->
    <el-container v-else class="container">
      <router-view/>
    </el-container>
  </div>
</template>

<script setup>
import {onBeforeUnmount, onMounted, reactive} from 'vue'
import {
  Shop,
  Menu,
  Clock,
  Goods,
  Service,
  OfficeBuilding,
  ChatLineRound,
  Document,
  Bell,
  Promotion,
  User,
  VideoCamera,
  Lock
  // 补充其他图标导入
} from '@element-plus/icons-vue'
import router from "./router/index.js";
import store from './store/index.js'
import AdminFooter from "./components/AdminFooter.vue";
import AdminHeader from "./components/AdminHeader.vue";
import ClientHeader from "./components/ClientHeader.vue";

import logoImage from '@/assets/images/logo1.png'

// 新增：移动端禁止手势缩放逻辑
const setupMobileZoomBlock = () => {
  const touchHandler = (e) => {
    if (e.touches.length > 1) e.preventDefault()
  }

  const gestureHandler = (e) => e.preventDefault()

  let lastTouchTime = 0
  const doubleTapHandler = (e) => {
    const now = Date.now()
    if (now - lastTouchTime <= 300) e.preventDefault()
    lastTouchTime = now
  }

  // 添加监听
  document.addEventListener('touchstart', touchHandler, {passive: false})
  document.addEventListener('gesturestart', gestureHandler)
  document.addEventListener('touchend', doubleTapHandler, {passive: false})

  // 返回清理函数
  return () => {
    document.removeEventListener('touchstart', touchHandler)
    document.removeEventListener('gesturestart', gestureHandler)
    document.removeEventListener('touchend', doubleTapHandler)
  }
}

// 新增：PC端禁止快捷键缩放逻辑
const setupDesktopZoomBlock = () => {
  const wheelHandler = (e) => {
    if (e.ctrlKey || e.metaKey) e.preventDefault()
  }

  const keydownHandler = (e) => {
    if ((e.ctrlKey || e.metaKey) && (e.key === '+' || e.key === '-')) {
      e.preventDefault()
    }
  }

  window.addEventListener('wheel', wheelHandler, {passive: false})
  window.addEventListener('keydown', keydownHandler)

  return () => {
    window.removeEventListener('wheel', wheelHandler)
    window.removeEventListener('keydown', keydownHandler)
  }
}

// 生命周期钩子整合
onMounted(() => {
  const cleanMobile = setupMobileZoomBlock()
  const cleanDesktop = setupDesktopZoomBlock()

  // 卸载时清理
  onBeforeUnmount(() => {
    cleanMobile()
    cleanDesktop()
  })
})

const state = reactive({
  adminMenu: false,
  clientMenu: false,
  defaultOpen: ['2', '3'],
  currentPath: '/',
});

// 开放路径
router.beforeEach(async (to, from, next) => {
  try {
    const isAuthenticated = store.getters.isAuthenticated;
    const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
    const isPublic = to.meta.layout === 'auth' || to.path === '/login' || to.path === '/register';

    // 已登录访问认证页
    if (isAuthenticated && isPublic) {
      let targetPath = '/';
      if (store.getters.isClient) {
        targetPath = '/client/home';
      } else if (store.getters.isAdmin) {
        targetPath = '/system/homePage';
      }
      return next(targetPath);
    }

    // 需要认证且未登录
    if (requiresAuth && !isAuthenticated) {
      if (!/^\/\w+/.test(to.fullPath)) {
        return next(`/login`);
      }
      return next(`/login?redirect=${encodeURIComponent(to.fullPath)}`);
    }

    // todo ！！！！！切记一定要先更新信息再放行
    // !!! 更新菜单显示状态
    state.adminMenu = store.getters.isAdmin;
    state.clientMenu = store.getters.isClient;
    state.currentPath = to.path;
    // 自动设置页面标题
    document.title = to.meta.title || '养老服务平台';
    next();
  } catch (error) {
    console.error('路由守卫错误:', error);
    next('/error'); // 跳转到错误页面
  }
});

</script>

<style scoped>
.client-container {
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.client-header {
  background-color: #3a8ee6;
  color: #ffffff;
  height: 60px;
  line-height: 60px;
  padding: 0 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.client-logo {
  height: 40px;
  margin-right: 20px;
}

.client-menu {
  display: flex;
  gap: 20px;
}

.client-menu a {
  color: #ffffff;
  text-decoration: none;
  font-size: 16px;
}

.client-menu a:hover {
  text-decoration: underline;
}

.layout {
  min-height: 100vh;
  background-color: #d4eaf7;
  overflow-y: auto; /* 确保页面内容超出视口时显示滚动条 */
}

.container {
  height: 100vh;
  display: flex;
  flex-direction: row;
}

.aside {
  width: 200px !important;
  background-color: #1F3A5F;
  overflow-y: auto; /* 确保侧边栏内容超出视口时显示滚动条 */
}

.head {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  width: 100%; /* 父容器宽度 */
  height: 64px; /* 父容器高度 */
}

.head img {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-width: 100%;
  max-height: 100%;
  width: auto;
  height: auto;
}

.line {
  border-top: 1px solid hsla(0, 0%, 100%, 0.05);
  border-bottom: 1px solid rgba(0, 0, 0, 0.2);
}

.content {
  display: flex;
  flex-direction: column;
  flex: 1; /* 占据剩余空间 */
  max-height: 100vh;
  overflow-y: auto; /* 确保内容超出视口时显示滚动条 */
}

.main {
  height: calc(100vh - 100px);
  overflow-y: auto; /* 确保主要内容超出视口时显示滚动条 */
  padding: 10px;
}
</style>

<style>
body {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  overflow-y: auto; /* 确保整个页面内容超出视口时显示滚动条 */
}

.el-menu {
  border-right: none !important;
}

.el-submenu {
  border-top: 1px solid hsla(0, 0%, 100%, 0.05);
  border-bottom: 1px solid rgba(0, 0, 0, 0.2);
}

.el-submenu:first-child {
  border-top: none;
}

.el-submenu [class^="el-icon-"] {
  vertical-align: -1px !important;
}

a {
  color: #409eff;
  text-decoration: none;
}

.el-pagination {
  text-align: center;
  margin-top: 20px;
}

.el-popper__arrow {
  display: none;
}
</style>
